package com.xzq.rongimtest;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 数据工具类
 */

public class DataUtil {

    /**
     * 哈希加密
     *
     * @param data
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String sha1(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(data.getBytes());
        StringBuffer buf = new StringBuffer();
        byte[] bits = md.digest();
        for (int bit : bits) {
            int a = bit;
            if (a < 0) {
                a += 256;
            }
            if (a < 16) {
                buf.append(0);
            }
            buf.append(Integer.toHexString(a));
        }
        return buf.toString();
    }

    /**
     * 获取指定长度的随机数，在前面补0
     * @param strLength
     * @return
     */
    public static String getFixLengthString(int strLength) {
        Random random = new Random();
        double randomNumber = (1 + random.nextDouble()) * Math.pow(10, strLength);
        String fixLengthString = String.valueOf(randomNumber);
        return fixLengthString.substring(2, strLength+1);
    }

}
